package com.rt.tmpt.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;



/**
 * @Author: wuxiaoyong
 * @Date: 2020/01/28
 * @Description: Decision决定的意思。
 * 有了权限资源(MyFilterInvocationSecurityMetadataSource)，知道了当前访问的url需要的具体权限，接下来就是决策当前的访问是否能通过权限验证了
 * MyAccessDecisionManager 自定义权限决策管理器
 **/
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

	/**
	 * @Description: 取当前用户的权限与这次请求的这个url需要的权限作对比，决定是否放行
	 * authentication 包含了当前的用户信息，包括拥有的权限,即之前UserDetailsService登录时候存储的用户对象
	 * object 就是FilterInvocation对象，可以得到request等web资源。
	 * configAttrList 是本次访问需要的权限。即上一步的 MyFilterInvocationSecurityMetadataSource 中查询核对得到的权限列表
	 * @Param: [auth, object, cas]
	 * @return: void
	 **/
	public void decide(Authentication authentication, Object object,
					   Collection<ConfigAttribute> configAttrList) throws AccessDeniedException,
			InsufficientAuthenticationException {

		/*System.out.println("authentication.getAuthorities()");
		System.out.println(authentication.getAuthorities());
		System.out.println("configAttrList");
		System.out.println(configAttrList);*/

		if(configAttrList==null || configAttrList.size()==0){
			//字不能修改，要和condition.jsp对应
			throw new AccessDeniedException("资源权限未分配");
		}

		Iterator<ConfigAttribute> iterator = configAttrList.iterator();
		while(iterator.hasNext()){
			ConfigAttribute configAttr = iterator.next();
			//当前请求需要的权限
			String needPermision = configAttr.getAttribute();
			System.out.println("====================needPermision:"+needPermision);
			//当前用户所具有的权限
			for(GrantedAuthority myAuth: authentication.getAuthorities()){
				//放行的URL
				if(needPermision.equals("_ACCESS")){
					return;
				}
				if(needPermision.equals(myAuth.getAuthority())){
					return;
				}
			}
		}

		System.out.println("没有权限访问！");
		throw new AccessDeniedException("没有权限访问！");
	}

	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}

}
